package com.company.oa.document.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.oa.document.dto.ApprovalDTO;
import com.company.oa.document.entity.ApprovalNode;
import com.company.oa.document.entity.ApprovalRecord;
import com.company.oa.document.entity.Document;
import com.company.oa.document.mapper.ApprovalNodeMapper;
import com.company.oa.document.mapper.ApprovalRecordMapper;
import com.company.oa.document.mapper.DocumentMapper;
import com.company.oa.document.service.ApprovalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 审批服务实现类
 */
@Service
public class ApprovalServiceImpl extends ServiceImpl<ApprovalRecordMapper, ApprovalRecord> implements ApprovalService {

    @Autowired
    private DocumentMapper documentMapper;

    @Autowired
    private ApprovalNodeMapper nodeMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean approveDocument(ApprovalDTO approvalDTO, Long approverId, String approverName) {
        Document document = documentMapper.selectById(approvalDTO.getDocumentId());
        if (document == null) {
            throw new RuntimeException("公文不存在");
        }

        // 检查公文状态
        if (document.getStatus() != 1) {
            throw new RuntimeException("公文不在审批中状态");
        }

        // 检查当前审批人
        if (!document.getCurrentApproverId().equals(approverId)) {
            throw new RuntimeException("您不是当前审批人");
        }

        // 查询当前审批节点
        LambdaQueryWrapper<ApprovalRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(ApprovalRecord::getDocumentId, document.getId())
                .orderByDesc(ApprovalRecord::getNode);
        ApprovalRecord lastRecord = getOne(recordWrapper, false);

        int currentNode = 1;
        if (lastRecord != null) {
            currentNode = lastRecord.getNode() + 1;
        }

        // 保存审批记录
        ApprovalRecord record = new ApprovalRecord();
        record.setDocumentId(document.getId());
        record.setApproverId(approverId);
        record.setApproverName(approverName);
        record.setResult(approvalDTO.getResult());
        record.setComment(approvalDTO.getComment());
        record.setNode(currentNode);
        record.setApprovalTime(LocalDateTime.now());
        save(record);

        // 更新公文状态
        if (approvalDTO.getResult() == 2) {
            // 驳回
            document.setStatus(3);
            document.setCurrentApproverId(null);
            document.setCurrentApproverName(null);
        } else {
            // 通过，查找下一个审批节点
            LambdaQueryWrapper<ApprovalNode> nodeWrapper = new LambdaQueryWrapper<>();
            nodeWrapper.eq(ApprovalNode::getFlowId, document.getApprovalFlowId())
                    .eq(ApprovalNode::getOrderNum, currentNode + 1);
            ApprovalNode nextNode = nodeMapper.selectOne(nodeWrapper);

            if (nextNode == null) {
                // 没有下一个节点，审批完成
                document.setStatus(2);
                document.setCurrentApproverId(null);
                document.setCurrentApproverName(null);
            } else {
                // 设置下一个审批人
                document.setCurrentApproverId(nextNode.getApproverId());
                document.setCurrentApproverName(nextNode.getApproverName());
            }
        }

        document.setUpdateTime(LocalDateTime.now());
        documentMapper.updateById(document);

        return true;
    }

    @Override
    public List<ApprovalRecord> getApprovalRecords(Long documentId) {
        LambdaQueryWrapper<ApprovalRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApprovalRecord::getDocumentId, documentId)
                .orderByAsc(ApprovalRecord::getNode);
        return list(wrapper);
    }

    @Override
    public IPage<ApprovalRecord> getMyApprovalRecords(int page, int size, Long userId) {
        Page<ApprovalRecord> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<ApprovalRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApprovalRecord::getApproverId, userId)
                .orderByDesc(ApprovalRecord::getApprovalTime);
        return page(pageParam, wrapper);
    }
} 